import subprocess


def check_pip():
    try:
        # 使用Popen来检查pip是否安装
        process = subprocess.Popen(['dpkg', '-l'], stdout=subprocess.PIPE, text=True)
        output, _ = process.communicate()
        if "python3-pip" in output:
            print("pip 已安装。")
        else:
            print("pip 未安装，正在尝试安装...")
            install_pip()
    except Exception as e:
        print(f"检查 pip 安装状态时出错: {e}")


def install_pip():
    try:
        print("更新源...")
        # 更新软件包列表，加上-y参数自动确认
        subprocess.check_call(['apt', 'update', '-y'])
        # 安装pip，加上-y参数自动确认
        subprocess.check_call(['apt', 'install', '-y', 'python3-pip'])
        print("pip 安装成功。")
    except subprocess.CalledProcessError as e:
        print("pip 安装失败。", e)


if __name__ == "__main__":
    check_pip()
